  package com.phonegapandroid;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.android.c2dm.C2DMBaseReceiver;

public class C2DMReceiver extends C2DMBaseReceiver {
	//public static final String c2dmRegId = "";
	//static final String PREFERENCE = "com.phonegap.Sample";

	public C2DMReceiver() {
		// Email address currently not used by the C2DM Messaging framework
		super("bvrapp@google.com");
	}

	@Override
	public void onRegistered(Context context, String registrationId)
			throws java.io.IOException {		
		try{
			
			
		Log.e("C2DM PhoneGap", "Registration ID arrived: Fantastic!!!");
		Log.e("C2DM PhoneGap", registrationId);
		}
		catch(Exception e)
		{
			Log.e("Error PhoneGap onRegister", e.getMessage());
		}
	};

	@Override
	protected void onMessage(Context context, Intent intent) {
		Log.e("C2DM", "Message: Recieved!!!");
		Bundle extras = intent.getExtras();
		if (extras != null) {
			String msg = extras.getString("data.c2dmsg");
			String msgTitle = extras.getString("data.c2dmsgtitle");
			String msgTicker = extras.getString("data.c2dmsgticker");		
			createNotification(msgTitle, msg, msgTicker);			
		}
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.e("C2DM", "Error occured!!!");
	}
	
	public void createNotification(String title, String text, String tickerttext)
	{
		int icon = R.drawable.notification_icon;        // icon from resources
		CharSequence tickerText = tickerttext;              // ticker-text
		long when = System.currentTimeMillis();         // notification time
		Context context = getApplicationContext();      // application Context
		CharSequence contentTitle = title;  // expanded message title
		CharSequence contentText = text;      // expanded message text

		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		// the next two lines initialize the Notification, using the configurations above
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		Notification notification = new Notification(icon, tickerText, when);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		notification.defaults |= Notification.DEFAULT_LIGHTS;
		//notification.defaults |= Notification.DEFAULT_SOUND;
		final int HELLO_ID = 1;
		mNotificationManager.notify(HELLO_ID, notification);
		Log.e("C2DM Notification", "Notification for Message Recieved Created");
	}
	
}